package com.clt.web.controller;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.clt.web.common.WeChat;
import com.clt.web.common.WeiXinPropertiesUtil;

/**
 * 扫一扫的控制器
 * 
 * @author Zhou Yingying
 * 
 */
@Controller
@RequestMapping("/scan")
public class ScanController {

	private final Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 
	 * @return ModelAndView对象
	 * @throws Exception
	 *             先得到页面需要的参数 再把参数传向页面
	 */
	@RequestMapping("/scanButton")
	public ModelAndView Scan(HttpServletRequest request){
		ModelAndView mav = new ModelAndView("scancode"); // 将mav对象传向scancode.jsp
		String jsapiTicket = null;
		String url = null;
		String timestamp = null;
		String nonceStr = null;
		String signature = null;
		try {
			jsapiTicket = WeChat.getTicket();
			mav.addObject("errorMSG", "");
		} catch (KeyManagementException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (NoSuchProviderException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (InterruptedException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (ExecutionException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		} catch (IOException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			mav.addObject("errorMSG", e.getMessage());
		}
		// 得到ticket
		url = request.getRequestURL().toString(); // 得到url
		log.info("获取本页面url为:{},ticket为:{}", url, jsapiTicket);
		// 得到包含url,jsapi_ticket,nonceStr,timestamp和signature的map
		Map<String, String> map = WeChat.jsApiSign(jsapiTicket, url);
		timestamp = map.get("timestamp");
		nonceStr = map.get("nonceStr");
		signature = map.get("signature");
		// 得到输入流中的AppId以供页面使用
		mav.addObject("appId", WeiXinPropertiesUtil.getAppId()); 
		mav.addObject("timestamp", timestamp);
		mav.addObject("nonceStr", nonceStr);
		mav.addObject("signature", signature);
		return mav;
	}
}
